package com.qyhl.party.party.study.subject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.party.R;
import com.qyhl.party.R2;
import com.qyhl.party.party.study.subject.item.PartyNewsLargeItemDelegate;
import com.qyhl.party.party.study.subject.item.PartyNewsLongItemDelegate;
import com.qyhl.party.party.study.subject.item.PartyNewsNormalItemDelegate;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.entity.news.UnionBean;
import com.qyhl.webtv.commonlib.utils.ResizableImageView;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.PARTY_SUBJECT)
public class PartySubjectActivity extends BaseActivity implements PartySubjectContract.PartySubjectView {
    @BindView(R2.id.catalog_recycler)
    RecyclerView catalogRecycler;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.top_recycler)
    RecyclerView topRecycler;
    @BindView(R2.id.title_layout)
    RelativeLayout titleLayout;

    RecyclerView subRecycler;
    TextView title;
    ResizableImageView cover;

    @Autowired(name = "style")
    int style;
    @Autowired(name = "title")
    String titleName;
    @Autowired(name = "logo")
    String logo;
    @Autowired(name = "catalogId")
    int catalogId;

    private PartySubjectPresenter mPresenter;

    private List<UnionBean> subList = new ArrayList<>();

    private List<NewsBean> mDataList = new ArrayList<>();

    private CommonAdapter<UnionBean> commonAdapter;

    private CommonAdapter<UnionBean> topAdapter;

    private MultiItemTypeAdapter<NewsBean> newsAdapter;

    private int ID = 0;

    private String innerCode;

    private HeaderAndFooterWrapper headerAndFooterWrapper;

    @Override
    protected int getContentView() {
        return R.layout.party_activity_subject;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarColor(R.color.white).statusBarDarkFont(true).fitsSystemWindows(true).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    @SuppressLint("InflateParams")
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);

        mPresenter = new PartySubjectPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));


        View headView = LayoutInflater.from(this).inflate(R.layout.party_header_subject, null);
        subRecycler = headView.findViewById(R.id.sub_recycler);
        title = headView.findViewById(R.id.title);
        cover = headView.findViewById(R.id.cover);

        title.setText(titleName);

        Glide.with(this)
                .load(logo)
                .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                .into(cover);

        topRecycler.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));

        topRecycler.setAdapter(topAdapter = new CommonAdapter<UnionBean>(this, R.layout.party_item_sub_tab, subList) {
            @Override
            protected void convert(ViewHolder holder, UnionBean unionBean, int position) {
                holder.setText(R.id.title, unionBean.getName());

                if (unionBean.isSelected) {
                    holder.setBackgroundRes(R.id.title, R.drawable.party_sub_tag_bg_on);
                    holder.setTextColorRes(R.id.title, R.color.white);
                } else {
                    holder.setBackgroundRes(R.id.title, R.drawable.party_sub_tag_bg_off);
                    holder.setTextColorRes(R.id.title, R.color.party_common_tab_off);
                }
            }
        });

        if (style == 0) {
            refresh.setEnableLoadMore(true);
            subRecycler.setVisibility(View.VISIBLE);

            subRecycler.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));

            subRecycler.setAdapter(commonAdapter = new CommonAdapter<UnionBean>(this, R.layout.party_item_sub_tab, subList) {
                @Override
                protected void convert(ViewHolder holder, UnionBean unionBean, int position) {
                    holder.setText(R.id.title, unionBean.getName());

                    if (unionBean.isSelected) {
                        holder.setBackgroundRes(R.id.title, R.drawable.party_sub_tag_bg_on);
                        holder.setTextColorRes(R.id.title, R.color.white);
                    } else {
                        holder.setBackgroundRes(R.id.title, R.drawable.party_sub_tag_bg_off);
                        holder.setTextColorRes(R.id.title, R.color.party_common_tab_off);
                    }
                }
            });

            commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
                    for (int i = 0; i < subList.size(); i++) {
                        subList.get(i).setSelected(i == position);
                    }
                    ID = 0;
                    innerCode = subList.get(position).getId();
                    mPresenter.getList(innerCode, ID + "");
                    commonAdapter.notifyDataSetChanged();
                    topAdapter.notifyDataSetChanged();
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                    return false;
                }
            });

            catalogRecycler.setLayoutManager(new LinearLayoutManager(this));

            DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
            divider.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(this, R.drawable.party_study_item_divider)));
            catalogRecycler.addItemDecoration(divider);
            //初始化适配器
            newsAdapter = new MultiItemTypeAdapter<NewsBean>(this, mDataList);
            newsAdapter.addItemViewDelegate(new PartyNewsLargeItemDelegate(this));
            newsAdapter.addItemViewDelegate(new PartyNewsLongItemDelegate(this));
            newsAdapter.addItemViewDelegate(new PartyNewsNormalItemDelegate(this));

            newsAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                    NewsBean newsBean = mDataList.get(i - 1);
                    switch (newsBean.getType()) {
                        case "1"://普通新闻
                        {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", newsBean.getID());
                            RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY, bundle);
                            ActionLogUtils.getInstance().onEvent(ActionConstant.PARTY_STUDY_NEWS);
                        }
                        break;
                        case "2"://图片新闻
                        {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", newsBean.getID());
                            bundle.putString("section", newsBean.getCatalogID());
                            RouterManager.router(ARouterPathConstant.PICTURE_NEWS_ACTIVITY, bundle);
                            ActionLogUtils.getInstance().onEvent(ActionConstant.PARTY_STUDY_NEWS);
                        }

                        break;
                        case "3"://直播
                        {
                            Bundle bundle = new Bundle();
                            bundle.putString("newsId", newsBean.getID());
                            bundle.putString("liveType", newsBean.getLivetype());
                            RouterManager.router(ARouterPathConstant.LIVE_NORMAL_ACTIVITY, bundle);
                            ActionLogUtils.getInstance().onEvent(ActionConstant.PARTY_STUDY_LIVE);
                        }
                        break;
                        case "4"://标题新闻
                        {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", newsBean.getID());
                            bundle.putString("title", newsBean.getTitle());
                            bundle.putString("url", newsBean.getRedirectURL());
                            RouterManager.router(ARouterPathConstant.ADV, bundle);
                            ActionLogUtils.getInstance().onEvent(ActionConstant.PARTY_STUDY_NEWS);
                        }
                        break;
                        case "5"://视频新闻
                        {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", newsBean.getID());
                            RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY, bundle);
                            ActionLogUtils.getInstance().onEvent(ActionConstant.PARTY_STUDY_LIVE);
                        }
                        break;
                        case "8"://互动直播
                            break;
                        case "101"://抓取新闻
                        {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", newsBean.getID());
                            RouterManager.router(ARouterPathConstant.NEWS_CATCH, bundle);
                            ActionLogUtils.getInstance().onEvent(ActionConstant.PARTY_STUDY_NEWS);
                        }
                        break;
                        default:
                            break;

                    }
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                    return false;
                }
            });


            headerAndFooterWrapper = new HeaderAndFooterWrapper<NewsBean>(newsAdapter);


        } else {
            refresh.setEnableLoadMore(false);
            subRecycler.setVisibility(View.GONE);

            catalogRecycler.setLayoutManager(new GridLayoutManager(this, 2));

            commonAdapter = new CommonAdapter<UnionBean>(this, R.layout.party_item_subject, subList) {
                @Override
                protected void convert(ViewHolder holder, UnionBean unionBean, int position) {
                    holder.setText(R.id.title, unionBean.getName());

                    ImageView cover = holder.getView(R.id.cover);

                    Glide.with(PartySubjectActivity.this)
                            .load(unionBean.getLogo())
                            .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                            .into(cover);
                }
            };

            commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
                    UnionBean bean = subList.get(position - 1);
                    ARouter.getInstance()
                            .build(ARouterPathConstant.PARTY_SUBJECT_SINGLE)
                            .withString("InnerCode", bean.getId())
                            .withString("title", bean.getName())
                            .withString("logo", bean.getLogo())
                            .navigation();

                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                    return false;
                }
            });

            headerAndFooterWrapper = new HeaderAndFooterWrapper<UnionBean>(commonAdapter);

        }
        headerAndFooterWrapper.addHeaderView(headView);
        catalogRecycler.setAdapter(headerAndFooterWrapper);

        mPresenter.getSub(catalogId + "");
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getSub(catalogId + "");
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getSub(catalogId + "");
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getList(innerCode, ID + "");
            }
        });

        topAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
                for (int i = 0; i < subList.size(); i++) {
                    subList.get(i).setSelected(i == position);
                }
                ID = 0;
                innerCode = subList.get(position).getId();
                mPresenter.getList(innerCode, ID + "");
                topAdapter.notifyDataSetChanged();
                commonAdapter.notifyDataSetChanged();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        catalogRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int[] location = new int[2];
                subRecycler.getLocationOnScreen(location);
                int y = location[1];
                if (style == 0 && y < subRecycler.getHeight()) {
                    topRecycler.setVisibility(View.VISIBLE);
                } else {
                    topRecycler.setVisibility(View.GONE);
                }
            }
        });
    }

    @OnClick(R2.id.back_btn)
    public void onClick() {
        finish();
    }

    @Override
    public void setSub(List<UnionBean> beanList) {
        subList.clear();
        subList.addAll(beanList);
        subList.get(0).setSelected(true);

        if (style == 0) {
            commonAdapter.notifyDataSetChanged();
            ID = 0;
            innerCode = subList.get(0).getId();
            mPresenter.getList(innerCode, ID + "");
        } else {
            loadMask.setStatus(LoadingLayout.Success);
            loadMask.setReloadButtonText("点击重试~");
            refresh.finishRefresh();
            headerAndFooterWrapper.notifyDataSetChanged();
        }
    }

    @Override
    public void setList(List<NewsBean> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");

        if (beanList != null && beanList.size() > 0) {
            if (ID == 0) {
                refresh.finishRefresh();
                mDataList.clear();
            } else {
                refresh.finishLoadMore();
            }
            mDataList.addAll(beanList);
            ID = Integer.parseInt(beanList.get(beanList.size() - 1).getID());
            headerAndFooterWrapper.notifyDataSetChanged();
        } else {
            refresh.finishRefresh();
            refresh.finishLoadMore();
            if (style == 0 && ID == 0) {
                mDataList.clear();
                headerAndFooterWrapper.notifyDataSetChanged();
            }
        }

    }

    @Override
    public void setError(String msg) {
        if (style == 0) {
            if (ID == 0) {
                refresh.finishRefresh();
                loadMask.setStatus(LoadingLayout.Error);
                loadMask.setErrorText(msg);
                loadMask.setReloadButtonText("点击重试~");
            } else {
                refresh.finishLoadMore();
                showToast(msg);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setErrorText(msg);
            loadMask.setReloadButtonText("点击重试~");
        }
    }
}
